<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.thymeleaf.org"
      layout:decorator="admin/include/layout_blank">
<head>
    <title>树形选择</title>
    <link href="/plugins/jquery-ztree/3.5.12/css/zTreeStyle/zTreeStyle.min.css" rel="stylesheet" type="text/css"/>
    <script src="/plugins/jquery-ztree/3.5.12/js/jquery.ztree.all-3.5.min.js" type="text/javascript"></script>
    <script type="text/javascript" th:inline="javascript">
        var key, lastValue = "", nodeList = [], type = getQueryString("type", [[${params['url']}]]);
        var isChecked = [[${params['checked']}]], allowSelectParent = [[${params['allowSelectParent']}]];
        var inputName = [[${params['inputName']}]], labelName = [[${params['labelName']}]];
        var tree, setting = {
            view:{
                selectedMulti:false,
                dblClickExpand:false
            },
            check:{
                enable:(isChecked == "Y"),
                nocheckInherit:true,
                chkStyle:"${checkbox}"
            },
            async:{
                enable:(type==3),
                url:""
            },
            data:{simpleData:{enable:true}},callback:{
                onClick:function(event, treeId, treeNode){
                    tree.expandNode(treeNode);
                },onCheck: function(e, treeId, treeNode){
                    var nodes = tree.getCheckedNodes(true);
                    for (var i=0, l=nodes.length; i<l; i++) {
                        tree.expandNode(nodes[i], true, false, false);
                    }
                    return false;
                },onAsyncSuccess: function(event, treeId, treeNode, msg){
                    var nodes = tree.getNodesByParam("pId", treeNode.id, null);
                    for (var i=0, l=nodes.length; i<l; i++) {
                        try{tree.checkNode(nodes[i], treeNode.checked, true);}catch(e){}
                        //tree.selectNode(nodes[i], false);
                    }
                    selectCheckNode();
                },onDblClick: function(){
                    if (isChecked != "Y") {
                        $("#submitBtn").trigger("click");
                    }
                }
            }
        };
        function expandNodes(nodes) {
            if (!nodes) return;
            for (var i=0, l=nodes.length; i<l; i++) {
                tree.expandNode(nodes[i], true, false, false);
                if (nodes[i].isParent && nodes[i].zAsync) {
                    expandNodes(nodes[i].children);
                }
            }
        }
        $(document).ready(function(){
            $.get([[${params['url']}]], function(zNodes){
                // 初始化树结构
                tree = $.fn.zTree.init($("#tree"), setting, zNodes);

                // 默认展开一级节点
//				var nodes = tree.getNodesByParam("level", 0);
//				for(var i=0; i<nodes.length; i++) {
//					tree.expandNode(nodes[i], true, false, false);
//				}
                // 默认展开全部节点
                tree.expandAll(true);

                //异步加载子节点（加载用户）
                var nodesOne = tree.getNodesByParam("isParent", true);
                for(var j=0; j<nodesOne.length; j++) {
                    tree.reAsyncChildNodes(nodesOne[j],"!refresh",true);
                }
                selectCheckNode();
            });
            key = $("#key");
            key.bind("focus", focusKey).bind("blur", blurKey).bind("change cut input propertychange", searchNode);
            key.bind('keydown', function (e){if(e.which == 13){searchNode();}});
//            setTimeout("search();", 300);

            $("#clearBtn").click(function(){
                $("#" + inputName, parent.document).val("");
                $("#" + labelName, parent.document).val("");
                closePage();
            });

            $("#submitBtn").click(function(){
                var ids = [], names = [], nodes = [];
                if (isChecked == "Y"){
                    nodes = tree.getCheckedNodes(true);
                }else{
                    nodes = tree.getSelectedNodes();
                }

                for(var i=0; i<nodes.length; i++) {
                    if (isChecked == "Y" && allowSelectParent == "N" && nodes[i].isParent) {
                        continue;
                    }
                    if (allowSelectParent == "N" && nodes[i].isParent) {
                        alert("不能选择父节点（"+nodes[i].name+"）请重新选择。");
                        return false;
                    }
                    ids.push(nodes[i].id);
                    names.push(nodes[i].name);
                    if (isChecked != "Y") {
                        break; // 如果为非复选框选择，则返回第一个选择
                    }
                }
                $("#" + inputName, parent.document).val(ids.join(",").replace(/u_/ig,""));
                $("#" + labelName, parent.document).val(names.join(","));

                closePage();
            });
        });

        function closePage() {
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
        }

        // 默认选择节点
        function selectCheckNode(){
            var ids = "${selectIds}".split(",");
            for(var i=0; i<ids.length; i++) {
                if (ids[i] != "") {
                    var node = tree.getNodeByParam("id", (type==3?"u_":"")+ids[i]);
                    if("${checked}" == "true"){
                        try{tree.checkNode(node, true, true);}catch(e){}
                        tree.selectNode(node, false);
                    }else{
                        tree.selectNode(node, true);
                    }
                }
            }
        }
        function focusKey(e) {
            if (key.hasClass("empty")) {
                key.removeClass("empty");
            }
        }
        function blurKey(e) {
            if (key.get(0).value === "") {
                key.addClass("empty");
            }
            searchNode(e);
        }

        //搜索节点
        function searchNode() {
            // 取得输入的关键字的值
            var value = $.trim(key.get(0).value);

            // 按名字查询
            var keyType = "name";

            // 如果和上次一次，就退出不查了。
            if (lastValue === value) {
                return;
            }

            // 保存最后一次
            lastValue = value;

            var nodes = tree.getNodes();
            // 如果要查空字串，就退出不查了。
            if (value == "") {
                showAllNode(nodes);
                return;
            }
            hideAllNode(nodes);
            nodeList = tree.getNodesByParamFuzzy(keyType, value);
            updateNodes(nodeList);
        }

        //隐藏所有节点
        function hideAllNode(nodes){
            nodes = tree.transformToArray(nodes);
            for(var i=nodes.length-1; i>=0; i--) {
                tree.hideNode(nodes[i]);
            }
        }

        //显示所有节点
        function showAllNode(nodes){
            nodes = tree.transformToArray(nodes);
            for(var i=nodes.length-1; i>=0; i--) {
                /* if(!nodes[i].isParent){
                 tree.showNode(nodes[i]);
                 }else{ */
                if(nodes[i].getParentNode()!=null){
                    tree.expandNode(nodes[i],false,false,false,false);
                }else{
                    tree.expandNode(nodes[i],true,true,false,false);
                }
                tree.showNode(nodes[i]);
                showAllNode(nodes[i].children);
                /* } */
            }
        }

        //更新节点状态
        function updateNodes(nodeList) {
            tree.showNodes(nodeList);
            for(var i=0, l=nodeList.length; i<l; i++) {

                //展开当前节点的父节点
                tree.showNode(nodeList[i].getParentNode());
                //tree.expandNode(nodeList[i].getParentNode(), true, false, false);
                //显示展开符合条件节点的父节点
                while(nodeList[i].getParentNode()!=null){
                    tree.expandNode(nodeList[i].getParentNode(), true, false, false);
                    nodeList[i] = nodeList[i].getParentNode();
                    tree.showNode(nodeList[i].getParentNode());
                }
                //显示根节点
                tree.showNode(nodeList[i].getParentNode());
                //展开根节点
                tree.expandNode(nodeList[i].getParentNode(), true, false, false);
            }
        }

        // 开始搜索
        function search() {
            $("#search").slideToggle(200);
            $("#txt").toggle();
            $("#key").focus();
        }

    </script>
</head>
<body>
<div class="content" layout:fragment="content">
    <div class="box">
        <div class="box-body" style="margin-bottom: 30px;">
            <div id="search" class="form-search" style="padding:5px 0 0 10px;">
                <label for="key" class="control-label" style="padding:5px 5px 3px 0;">关键字：</label>
                <input type="text" class="empty" id="key" name="key" maxlength="50" style="width:110px;">
            </div>
            <div id="tree" class="ztree" style="padding:5px 10px;"></div>
        </div>
        <div class="box-footer" style="position: fixed;bottom: 5px;width: 90%;">
            <button class="btn-xs btn-default" type="button" id="clearBtn">
                清除
            </button>
            <button class="btn-xs btn-primary pull-right" type="button" id="submitBtn">
                提交
            </button>
        </div>
    </div>

</div>
</body>
</html>